//
//  YWObserverTableViewController.m
//  maintain
//
//  Created by 烟雨云渊 on 16/11/21.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWObserverTableViewController.h"
#import "UIColor+CustomColors.h"
#import "UIView+Extension.h"
#import "YWMacro.h"
#import "YWConst.h"
#import "YWNavigationController.h"
#import "MBProgressHUD.h"
#import "YWCommonTool.h"

#import "YWObserverCollectionCell.h"

#import "YWHandler.h"
#import "YWLoginTool.h"
#import "YWLoginUser.h"
#import "YWSelectContactTableViewController.h"
#import "YWRemoveObserverTableViewController.h"
#import "YWEwinManager.h"
#import "YWReply.h"
#import "YWReplyManager.h"

@interface YWObserverTableViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,YWContactVCSelectContactDelegate,YWRemoveObserverTableViewDelegate,UITextFieldDelegate>{
}
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *observerDateSource;
@property (nonatomic, assign) BOOL isCreater;

@property (nonatomic, weak) MBProgressHUD* HUD;
@property (nonatomic, strong) NSArray *creatersAndExecutorsAndReporters;
@end

@implementation YWObserverTableViewController
- (instancetype)init{
    return  [super initWithStyle:UITableViewStyleGrouped];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedString(@"missionObserver", nil);//@"任务参与人";
    
    [self setupDate];
    [self configCollectionView];
    [self configTableView];
    
}
- (void)setupDate{
    NSMutableArray *tempArray = [NSMutableArray array];
    [tempArray addObjectsFromArray:_creaters];
    [tempArray addObjectsFromArray:_reporters];
    
    YWLoginUser *currentUser = [YWLoginTool loginUser];
    NSInteger uniqueId = currentUser.uniqueId;
    NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K = %ld", @"uniqueId", uniqueId];
    NSArray *creatorArray = _creaters.count==0?_reporters:_creaters;
    NSArray *array = [[creatorArray filteredArrayUsingPredicate:searchPredicate] mutableCopy];
    if (array.count>0) {
        _isCreater = YES;
    }
    
    [tempArray addObjectsFromArray:_executors];
    _creatersAndExecutorsAndReporters = [[NSArray alloc] initWithArray:tempArray];
    
    [tempArray addObjectsFromArray:_observers];
    for (YWHandler *handler in tempArray) {
        NSInteger uniqueId = handler.uniqueId;
        NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K = %ld", @"uniqueId", uniqueId];
        NSArray *array = [[self.observerDateSource filteredArrayUsingPredicate:searchPredicate] mutableCopy];
        if (array.count==0) {
            [self.observerDateSource addObject:handler];
        }
    }
}

- (NSMutableArray *)observerDateSource{
    if (!_observerDateSource) {
        _observerDateSource = [NSMutableArray array];
    }
    return _observerDateSource;
}

- (void)configCollectionView {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    CGFloat _margin = 15;//item之间的间隔
    CGFloat _gap = 20;//和屏幕的间隔
    NSInteger countOfRow = SCREEN_WIDTH>320 ? 5 : 4;
    CGFloat _itemWH = ((self.view.width - (countOfRow-1) * _margin) - _gap*2 )/ countOfRow;
    layout.itemSize = CGSizeMake(_itemWH, _itemWH+18);
    layout.minimumInteritemSpacing = _margin;
    layout.minimumLineSpacing = _margin;
    int count = _isCreater ? (int)_observerDateSource.count+2:(int)_observerDateSource.count+1;
    
    CGFloat selfSizeHeight = (_itemWH+18)*((count-1)/countOfRow+1) + _margin*((count-1)/countOfRow) +_margin*2;
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, selfSizeHeight) collectionViewLayout:layout];
    //CGFloat rgb = 244 / 255.0;
    _collectionView.alwaysBounceVertical = YES;
    _collectionView.backgroundColor = [UIColor whiteColor];//[UIColor colorWithRed:rgb green:rgb blue:rgb alpha:1.0];
    _collectionView.contentInset = UIEdgeInsetsMake(_margin, 20, _margin, 20);
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    _collectionView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    [_collectionView registerClass:[YWObserverCollectionCell class] forCellWithReuseIdentifier:@"YWObserverCollectionCell"];
}

- (void)configTableView{
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    self.tableView.separatorColor = [UIColor customLineColor];
    self.tableView.rowHeight = 44.0f;
    
    self.tableView.tableHeaderView = _collectionView;
}

#pragma mark - UICollectionView data source
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _isCreater ? _observerDateSource.count+2 : _observerDateSource.count+1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    YWObserverCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"YWObserverCollectionCell" forIndexPath:indexPath];
    if (_isCreater) {
        if (indexPath.row == _observerDateSource.count) {
            cell.addBtn = YES;
        }else if (indexPath.row == _observerDateSource.count+1){
            cell.deleteBtn = YES;
        }else{
            YWHandler *handler = _observerDateSource[indexPath.row];
            cell.handler = handler;
        }
    }else{
        if (indexPath.row == _observerDateSource.count){
            cell.addBtn = YES;
        }else{
            YWHandler *handler = _observerDateSource[indexPath.row];
            cell.handler = handler;
        }
    }
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    //点击加号和剪好事件
    if (_isCreater) {
        if (indexPath.row == _observerDateSource.count) {
            //添加
            YWSelectContactTableViewController *selectUserVC = [[YWSelectContactTableViewController alloc] init];
            selectUserVC.allJoinUser = _observerDateSource;
            selectUserVC.delegate = self;
            selectUserVC.titleName = NSLocalizedString(@"selectObserver", nil);//@"选择参与人";
            YWNavigationController *nav = [[YWNavigationController alloc] initWithRootViewController:selectUserVC];
            [self presentViewController:nav animated:YES completion:nil];
        }else if (indexPath.row == _observerDateSource.count+1){
            //删除
            YWRemoveObserverTableViewController *removeObserverVC = [[YWRemoveObserverTableViewController alloc] init];
            NSMutableArray *tempArray = [NSMutableArray array];
            [tempArray addObjectsFromArray:_observerDateSource];
            [tempArray removeObjectsInArray:_creatersAndExecutorsAndReporters];
            removeObserverVC.dataSource = tempArray;
            removeObserverVC.delegate = self;
            YWNavigationController *nav = [[YWNavigationController alloc] initWithRootViewController:removeObserverVC];
            [self presentViewController:nav animated:YES completion:nil];
        }else{
            //YWHandler *handler = _observerDateSource[indexPath.row];
            
        }
    }else{
        if (indexPath.row == _observerDateSource.count){
            //添加
            YWSelectContactTableViewController *selectUserVC = [[YWSelectContactTableViewController alloc] init];
            selectUserVC.allJoinUser = _observerDateSource;
            selectUserVC.titleName = NSLocalizedString(@"selectObserver", nil);//@"选择参与人";
            selectUserVC.delegate = self;
            YWNavigationController *nav = [[YWNavigationController alloc] initWithRootViewController:selectUserVC];
            [self presentViewController:nav animated:YES completion:nil];
        }else{
            //YWHandler *handler = _observerDateSource[indexPath.row];
            
        }
    }
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellId = @"YWObserverTableVCCellIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (cell==nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 50.0f;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    return NSLocalizedString(@"addNewObserverTips", nil);
}
#pragma mark - YWContactVCSelectContactDelegate
- (void)selectSingleContact:(YWHandler *)contact{
    if (contact) {
        NSInteger uniqueId = contact.uniqueId;
        NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K = %ld", @"uniqueId", uniqueId];
        NSArray *array = [[_observerDateSource filteredArrayUsingPredicate:searchPredicate] mutableCopy];
        if (array.count>0) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"thisUserIsObserver", nil)];
        }else{
            NSString *tip = [NSString stringWithFormat:@"%@%@%@%@%@",NSLocalizedString(@"youWill", nil),contact.userName?:@"",NSLocalizedString(@"joinObserverAndAfterJoin", nil),contact.userName?:@"",NSLocalizedString(@"canFollowMissionProgress", nil)];
            UIAlertController* alertController= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"tips", nil) message:tip preferredStyle:UIAlertControllerStyleAlert];
            [self presentViewController:alertController animated:YES completion:nil];
            [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField){
                textField.clearButtonMode = UITextFieldViewModeWhileEditing;
                textField.placeholder = NSLocalizedString(@"leaveMessage", nil);//@"给他留句话吧";
            }];
            [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil) style:UIAlertActionStyleCancel handler:nil]];
            [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self.HUD show:YES];
                UITextField *textField = alertController.textFields.firstObject;
                NSString *replyContent = [textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
                if (replyContent.length == 0) {
                    [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"pleaseEnterNote", nil)];
                    return ;
                }
                if (replyContent.length>100) {
                    [self.HUD hide:YES];
                    [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoteMax, nil)];
                }else if ([YWCommonTool isContainsEmoji:replyContent]) {
                    [self.HUD hide:YES];
                    [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextCantContainEmoji, nil)];
                }else{
                    YWReply * reply = [self createReply:contact replyContent:replyContent];
                    NSString *url = [YWCommonTool postReplyUrl];
                    [[YWReplyManager shareManager] commitReplys:reply url:url WithComplete:^(BOOL success) {
                        //发通知
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [[NSNotificationCenter defaultCenter] postNotificationName:KPostMissionAddObserverNotification object:contact];
                        });
                        //        if (success) {
                        //            [self.tableView reloadData];
                        //        }
                    }];
                }
                [[YWEwinManager shareManager] addObserver:contact relationId:self.relationId type:self.type complete:^(BOOL succeed) {
                    [self.HUD hide:YES];
                    if (succeed) {
                        [_observerDateSource addObject:contact];
                        [self resetCollectionViewHeight];
                        [_collectionView reloadData];
                        self.tableView.tableHeaderView = _collectionView;
                        //发通知
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [[NSNotificationCenter defaultCenter] postNotificationName:KPostMissionAddObserverNotification object:contact];
                        });
                        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"addSucceed", nil)];
                    }else{
                        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"failedAndTryAgain", nil)];
                    }
                }];
                [self dismissViewControllerAnimated:YES completion:nil];
            }]];
        }
    }
}

-(YWReply *)createReply:(YWHandler*)contact replyContent:(NSString*)content{
    YWReply *reply = [[YWReply alloc]init];
    reply.replyId = 0;//提交成功后id会被服务端返回的id替换
    reply.relationId = [_relationId integerValue];
    reply.relationType = _type;
    reply.content = content;
    reply.atUser = contact;
    YWHandler *replier = [[YWHandler alloc] init];
    replier.uniqueId = [YWLoginTool loginUser].uniqueId;
    reply.replier = replier;
    reply.replyTime = [[NSDate date] timeIntervalSince1970]*1000;
    reply.isRead = YES;
    return reply;
}

#pragma mark - YWRemoveObserverTableViewDelegate
- (void)deleteUser:(YWHandler *)contact{
    if (contact) {
        [self.HUD show:YES];
        [[YWEwinManager shareManager] deleteObserver:contact relationId:_relationId type:_type complete:^(BOOL succeed) {
            [self.HUD hide:YES];
            if (succeed) {
                [_observerDateSource removeObject:contact];
                [self resetCollectionViewHeight];
                [_collectionView reloadData];
                self.tableView.tableHeaderView = _collectionView;
                //发通知
                dispatch_async(dispatch_get_main_queue(), ^{
                    [[NSNotificationCenter defaultCenter] postNotificationName:KPostMissionDeleteObserverNotification object:contact];
                });
                [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"deleteSucceed", nil)];
            }else{
                [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"failedAndTryAgain", nil)];
            }
        }];
    }
}

- (void)resetCollectionViewHeight{
    CGFloat _margin = 15;//item之间的间隔
    CGFloat _gap = 20;//和屏幕的间隔
    NSInteger countOfRow = SCREEN_WIDTH>320 ? 5 : 4;
    CGFloat _itemWH = ((self.view.width - (countOfRow-1) * _margin) - _gap*2 )/ countOfRow;
    int count = _isCreater ? (int)_observerDateSource.count+2:(int)_observerDateSource.count+1;
    CGFloat selfSizeHeight = (_itemWH+18)*((count-1)/countOfRow+1) + _margin*((count-1)/countOfRow) +_margin*2;
    _collectionView.height = selfSizeHeight;
}

- (MBProgressHUD*)HUD
{
    if (!_HUD) {
        MBProgressHUD* hud = [[MBProgressHUD alloc] initWithView:[UIApplication sharedApplication].keyWindow];
        hud.labelFont = kHUDLabelFont;
        hud.labelText = NSLocalizedString(kTextBeingProcessed, nil);
        hud.dimBackground = YES;
        //hud.animationType = MBProgressHUDAnimationZoom;
        _HUD = hud;
        _HUD.tag = kMBProgressHUDTag;
        [self.navigationController.view addSubview:hud];
    }
    return _HUD;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
